package com.ruoyi.sql;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruoyi.query.entity.Query;
import com.ruoyi.query.entity.QueryDtl;
import com.ruoyi.query.entity.QueryTable;
import com.ruoyi.util.DynamicUtil;
import com.ruoyi.util.ReflectUtil;
import com.ruoyi.util.SerializableFunction;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/**
 * **********************
 * * Author: XiaShiLong *
 * * Date  : 2021-05-15 *
 * * Time  : 13:18      *
 * * to    : lz&xm      *
 * **********************
 **/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class QueryUtil<T> {

    private Class<T> classes;

    private final List<QueryDtl> queryDtls = new ArrayList<>();

    private QueryUtil(Class<T> classes) {
        this.classes = classes;
    }

    public static <T> QueryUtil<T> builder(Class<T> classes) {
        return new QueryUtil<>(classes);
    }

    public QueryUtil<T> eq(SerializableFunction<T, ?> function, Object value) {
        queryDtls.add(
                QueryDtl.builder()
                        .tableName(TableUtil.getTableName(classes))
                        .tableColumnName(StringUtils.camelToUnderline(ReflectUtil.getFieldName(function)))
                        .value1(value.toString())
                        .dictQueryType(1)
                        .build()
        );
        return this;
    }

    public String build() {
        return getDynamicSqlForQuery(
                Query.builder()
                        .classPath(classes.getName())
                        .detailList(queryDtls)
                        .build()
        );
    }

    public static String getDynamicSqlForQuery(Query query) {
        Class<?> classes = ReflectUtil.getClass(query.getClassPath());
        StringBuilder sb = new StringBuilder(QueryTable.sql(QueryTable.create(classes, true, void.class)));
        if (null != query.getDetailList() && !query.getDetailList().isEmpty()) {
            sb.append(" WHERE 1=1 ");
            query.getDetailList().forEach(
                    d -> DynamicUtil.queryTypeWhere(new WhereEntity(d), sb)
            );
        }
        sb.append(" ORDER BY ").append(TableUtil.getTableName(classes)).append(".id");
        return sb.toString();
    }
}
